<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="供货点名称" prop="dhName">
      <el-input v-model="dataForm.dhName" placeholder="供货点名称"></el-input>
    </el-form-item>
    <div style="display: flex">
      <div>
        <div>
          <el-select
            v-model="keywords"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="loading"
            :clearable="true"
            size="mini"
            @change="currentSelect"
            style="width: 500px"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item"
              class="one-text"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.district
              }}</span>
            </el-option>
          </el-select>
        </div>
        <div id="container" class="container"></div>
      </div>
      
    </div>
    <el-form-item label="供货点地址" prop="ghSite">
      <el-input v-model="dataForm.ghSite" placeholder="供货点地址"></el-input>
    </el-form-item>
    <el-form-item label="经度" prop="ghLongitude">
      <el-input v-model="dataForm.ghLongitude" placeholder="经度"></el-input>
    </el-form-item>
    <el-form-item label="纬度" prop="ghLatitude">
      <el-input v-model="dataForm.ghLatitude" placeholder="纬度"></el-input>
    </el-form-item>
    <el-form-item label="供货点电话" prop="ghPhone">
      <el-input v-model="dataForm.ghPhone" placeholder="供货点电话"></el-input>
    </el-form-item>
    <el-form-item label="供货点状态" prop="ghState">
      <el-input v-model="dataForm.ghState" placeholder="供货点状态"></el-input>
    </el-form-item>

    <el-form-item label="供货点账号" prop="ghUser">
      <el-input v-model="dataForm.ghUser" placeholder="供货点账号"></el-input>
    </el-form-item>
    <el-form-item label="供货点密码" prop="ghPwd">
      <el-input v-model="dataForm.ghPwd" placeholder="供货点密码"></el-input>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: '5ac14c55bcc6abbc1195a1aa036e7d96'
}
  export default {
    data () {
      return {
        // 地图实例
      map: null,
      // 标记点
      marker: '',
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      // 搜索关键字
      keywords: '',
      // 位置信息
      form: {
        lng: '',
        lat: '',
        address: '',
        adcode: '' // 地区编码
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
        visible: false,
        dataForm: {
          ghId: 0,
          dhName: '',
          ghSite: '',
          ghLongitude: '',
          ghLatitude: '',
          ghPhone: '',
          ghState: '',
          isDelete: '',
          ghUser: '',
          ghPwd: ''
        },
        dataRule: {
          dhName: [
            { required: true, message: '供货点名称不能为空', trigger: 'blur' }
          ],
          ghSite: [
            { required: true, message: '供货点地址不能为空', trigger: 'blur' }
          ],
          ghLongitude: [
            { required: true, message: '经度不能为空', trigger: 'blur' }
          ],
          ghLatitude: [
            { required: true, message: '纬度不能为空', trigger: 'blur' }
          ],
          ghPhone: [
            { required: true, message: '供货点电话不能为空', trigger: 'blur' }
          ],
          ghState: [
            { required: true, message: '供货点状态不能为空', trigger: 'blur' }
          ],
          isDelete: [
            { required: true, message: '逻辑删除不能为空', trigger: 'blur' }
          ],
          ghUser: [
            { required: true, message: '供货点账号不能为空', trigger: 'blur' }
          ],
          ghPwd: [
            { required: true, message: '供货点密码不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    mounted () {
    this.initMap()
  },
    methods: {
      initMap () {
      AMapLoader.load({
        // 你申请的Key
        key: '3a1a72abe401b7bb9e9099edd26526cd',
        version: '2.0',
        // 需要用到的插件
        plugins: ['AMap.Geocoder', 'AMap.AutoComplete']
      })
        .then((AMap) => {
          this.map = new AMap.Map('container', {
            viewMode: '3D', // 是否为3D地图模式
            zoom: 5, // 初始化地图级别
            center: [105.602725, 37.076636] // 初始化地图中心点位置
          })
          // 地址逆解析插件
          this.geoCoder = new AMap.Geocoder({
            city: '010', // 城市设为北京，默认：“全国”
            radius: 1000 // 范围，默认：500
          })
          // 搜索提示插件
          this.AutoComplete = new AMap.AutoComplete({ city: '全国' })
          // 点击获取经纬度;
          this.map.on('click', (e) => {
            // 获取经纬度
            this.dataForm.ghLongitude = e.lnglat.lng
            this.dataForm.ghLatitude = e.lnglat.lat
            // 清除点
            this.removeMarker()
            // 标记点
            this.setMapMarker()
          })
        })
        .catch((err) => {
          // 错误
          console.log(err)
        })
    },
    // 标记点
    setMapMarker () {
      // 自动适应显示想显示的范围区域
      this.map.setFitView()
      // eslint-disable-next-line no-undef
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat]
      })
      // 逆解析地址
      this.toGeoCoder()
      this.map.setFitView()
      this.map.add(this.marker)
    },
    // 清除点
    removeMarker () {
      if (this.marker) {
        this.map.remove(this.marker)
      }
    },
    // 逆解析地址
    toGeoCoder () {
      const lnglat = [this.form.lng, this.form.lat]
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.dataForm.ghSite = result.regeocode.formattedAddress
        }
      })
    },
    // 搜索
    remoteMethod (query) {
      console.log(query)
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.AutoComplete.search(query, (status, result) => {
            this.options = result.tips
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    // 选中提示
    currentSelect (val) {
      // 清空时不执行后面代码
      if (!val) {
        return
      }
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        address: val.district + val.address,
        adcode: val.adcode
      }
      // 清除点
      this.removeMarker()
      // 标记点
      this.setMapMarker()
    },
      init (id) {
        this.dataForm.ghId = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.ghId) {
            this.$http({
              url: this.$http.adornUrl(`/supplier/ssmsupplier/info/${this.dataForm.ghId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.dhName = data.ssmSupplier.dhName
                this.dataForm.ghSite = data.ssmSupplier.ghSite
                this.dataForm.ghLongitude = data.ssmSupplier.ghLongitude
                this.dataForm.ghLatitude = data.ssmSupplier.ghLatitude
                this.dataForm.ghPhone = data.ssmSupplier.ghPhone
                this.dataForm.ghState = data.ssmSupplier.ghState
                this.dataForm.isDelete = data.ssmSupplier.isDelete
                this.dataForm.ghUser = data.ssmSupplier.ghUser
                this.dataForm.ghPwd = data.ssmSupplier.ghPwd
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/supplier/ssmsupplier/${!this.dataForm.ghId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'ghId': this.dataForm.ghId || undefined,
                'dhName': this.dataForm.dhName,
                'ghSite': this.dataForm.ghSite,
                'ghLongitude': this.dataForm.ghLongitude,
                'ghLatitude': this.dataForm.ghLatitude,
                'ghPhone': this.dataForm.ghPhone,
                'ghState': this.dataForm.ghState,
                'isDelete': this.dataForm.isDelete,
                'ghUser': this.dataForm.ghUser,
                'ghPwd': this.dataForm.ghPwd
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
<style scoped>
.container {
    width: 700px;
    height: 300px;
  }
</style>